package bootstrap

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
)

var (
	DiscoverConfig DiscoverConf
	HttpConfig     HttpConf
	RpcConfig      RpcConf
)

type DiscoverConf struct {
	Host        string
	Port        string
	ServiceName string
	Weight      int
	InstanceId  string
}

type HttpConf struct {
	Host string
	Port string
}

type RpcConf struct {
	Host string
	Port string
}

func init() {
	viper.AutomaticEnv()
	initConfig()

	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("err:%s\n", err)
	}

	if err := subParse("discover", &DiscoverConfig); err != nil {
		log.Fatal("Fail to parse Discover config", err)
	}
	if err := subParse("http", &HttpConfig); err != nil {
		log.Fatal("Fail to parse Http config", err)
	}
	//if err := subParse("config", &ConfigServerConfig); err != nil {
	//	log.Fatal("Fail to parse config server", err)
	//}

	if err := subParse("rpc", &RpcConfig); err != nil {
		log.Fatal("Fail to parse rpc server", err)
	}
}

func initConfig() {
	viper.SetConfigName("bootstrap")
	viper.AddConfigPath("./")
	viper.SetConfigType("yaml")
}

func subParse(key string, value interface{}) error {

	log.Println("Config pre:", key)
	sub := viper.Sub(key)
	sub.SetEnvPrefix(key)
	return sub.Unmarshal(value)
}
